<template>
	<view>
		<view v-if="!loading && listData.length">
			<slot :data="listData"></slot>
			<u-loadmore :loading-icon="loadIcon" :status="loadStatus" v-if="loadmoreTips" />
		</view>
		<k-loading :loadIcon="loadIcon" :loading="loading" v-else></k-loading>
	</view>
</template>

<script>
	import http from "@/common/js/http.js";
	export default {
		name: "k-list",
		props: {
			api: {
				type: String,
				default: ""
			},
			list: {
				type: Array,
				default: _ => []
			},
			params: {
				type: Object,
				default: _ => ({})
			},
			method: {
				type: String,
				default: "post"
			},
			loadIcon: {
				type: String,
				default: "semicircle"
			},
			loadmoreTips: {
				type: Boolean,
				default: false
			},
			listKey: {
				type: String,
				default: "data.list"
			},
			// 处理列表数组
			handleData: {
				type: Function
			}
		},
		data() {
			return {
				listData: [],
				paging: {
					page: 1,
					listRows: 20
				},
				loading: false,
				isMore: false,
				requestCount: 0,
			};
		},
		computed: {
			loadStatus() {
				return this.isMore ? this.loading ? "loading " : "loadmore" : "nomore"
			}
		},
		created() {
			if(this.api){
				this.getData();
			}else{
				this.loadData();
			}
		},
		watch: {
			list() {
				this.loadData()
			},
		},
		methods: {
			refresh() {
				this.loadData(1);
			},
			getData(refresh = 0, parameter = {}) {
				if (refresh || !this.listData.length) this.loading = true;
				http[this.method](this.api, {
					...this.paging,
					...this.params,
					...parameter
				}).then(res => {
					console.log("列表数据",res);
					this.$emit("getResource",res);
					let data = this.$k.getObjDeepProps(res, this.listKey);
					if (typeof this.handleDataCall == "function") data = this.handleDataCall(data);
					if (refresh) {
						this.listData = data;
					} else {
						this.listData.push(...data);
					}
					this.isMore = data.length >= this.paging.listRows;
					this.requestCount++;
				}).finally(_ => {
					this.loading = false;
				});
			},
			loadData(refresh = 0) {
				if (this.api) {
					if (this.isMore) {
						this.paging.page++;
						this.getData(refresh);
					}
				} else {
					this.listData = this.list;
				}
			},
			changeList(i,v){
				this.$set(this.listData,i,v);
			}
		}
	}
</script>

<style lang="scss">

</style>